package handlers

import (
	"net/http"
	"qimo_work/repositories"
	"strconv"

	"github.com/gin-gonic/gin"
)

// LikePost 点赞文章
func LikePost(c *gin.Context) {
	// 获取文章 ID
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的文章 ID"})
		return
	}

	// 点赞文章，更新点赞数
	err = repositories.UpdatePostMetrics(uint(id), 0, 1, 0)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "点赞失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "点赞成功"})
}
func FavoritePost(c *gin.Context) {
	// 从上下文中获取 userID
	userID, exists := c.Get("userID")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "用户未登录"})
		return
	}

	// 断言为 uint
	userIDUint, ok := userID.(uint)
	if !ok {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "用户 ID 类型错误"})
		return
	}

	// 获取文章 (post) ID
	postID, err := strconv.Atoi(c.Param("id")) // 修改为 postID
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的文章 ID"})
		return
	}

	// 调用 AddToFavorites 函数处理收藏操作
	err = repositories.AddToFavorites(userIDUint, uint(postID)) // 修改为 postID
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "收藏失败", "details": err.Error()})
		return
	}

	// 如果收藏成功，返回成功响应
	c.JSON(http.StatusOK, gin.H{"message": "收藏成功"})
}

// handlers/favorite_handler.go
func GetUserFavoritePosts(c *gin.Context) {
	// 获取用户 ID
	userID, exists := c.Get("userID")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "用户未登录"})
		return
	}

	userIDUint, ok := userID.(uint)
	if !ok {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "用户 ID 类型错误"})
		return
	}

	// 查询收藏的文章
	favorites, err := repositories.GetUserFavorites(userIDUint)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取收藏文章失败", "details": err.Error()})
		return
	}

	// 组装返回的数据
	var favoriteList []gin.H
	for _, fav := range favorites {
		favoriteList = append(favoriteList, gin.H{
			"id":         fav.ID,
			"user_id":    fav.UserID,
			"username":   fav.Username, // 关联查询获取的用户名
			"post_id":    fav.PostID,
			"post_title": fav.PostTitle, // 关联查询获取的文章标题
			"created_at": fav.CreatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	c.JSON(http.StatusOK, gin.H{
		"message":   "获取成功",
		"favorites": favoriteList,
	})
}

// 取消收藏文章
func RemoveFavoritePost(c *gin.Context) {

	// 获取文章 ID
	postID, err := strconv.Atoi(c.Param("post_id"))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的文章 ID"})
		return
	}

	// 删除收藏记录
	err = repositories.RemoveFromFavorites(uint(postID))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "取消收藏失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "取消收藏成功"})
}
